/**
 * 倒计时指令。在dom元素上加上这个标签，可以实现倒计时，disabled等判定
 * 用法:
 *
 * <button send-sms="LOGIN_SMS" ng-click="sendSMS()">发送验证码</button>
 *
 *    $scope.sendSMS = function () {//发送验证码
 *      $scope.$broadcast('LOGIN_SMS',{count:5});
 *    };
 *
 *    count参数是倒计时多少秒。默认5秒
 */
APP.directive('sendSms', ['$timeout', '$stateParams', 'AreaService', '$state',
  function ($timeout, $stateParams, AreaService, $state) {
    return {
      restrict: 'A',
      link: function (scope, element, attr) {
        var BROADCAST_ID = attr.sendSms;
        var countMax = 5;
        var count = countMax;
        var textReady = '获取验证码';
        var textCount = '秒后重发';
        scope.$on(BROADCAST_ID, function (event, arg) {
          if (arg && arg.count) {
            count = countMax = arg.count;
          }
          element[0].disabled = true;
          element[0].innerText = count + textCount;
          var timerId = setInterval(function () {
            if (count > 0) {
              count = count - 1;
              element[0].innerText = count + textCount;
            } else {
              count = countMax;
              element[0].disabled = false;
              element[0].innerText = textReady;
              clearInterval(timerId);//停止计时
            }
          }, 1000);
        });
      }
    }
  }]);
